<!DOCTYPE html>
<html lang="en-US">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>Android消息机制解析 | 江流</title>
    <meta name="generator" content="VuePress 1.8.2">
    <link rel="icon" href="/favicon.ico">
    <script>
	  var _hmt = _hmt || [];
	  (function() {
	    var hm = document.createElement("script");
		hm.src = "https://hm.baidu.com/hm.js?d53065bd59576478808301d9b305d57a";
	    var s = document.getElementsByTagName("script")[0]; 
	    s.parentNode.insertBefore(hm, s);
	  })();
	  </script>        
	  </script>
    <meta name="description" content="我的知识存储空间，不大不小刚刚好！">
    <meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no">
    
    <link rel="preload" href="/assets/css/0.styles.f7444686.css" as="style"><link rel="preload" href="/assets/js/app.371ed010.js" as="script"><link rel="preload" href="/assets/js/3.fe7e7b6d.js" as="script"><link rel="preload" href="/assets/js/1.adb5634c.js" as="script"><link rel="preload" href="/assets/js/20.8284a0ff.js" as="script"><link rel="prefetch" href="/assets/js/10.1f1951c3.js"><link rel="prefetch" href="/assets/js/100.61abc83e.js"><link rel="prefetch" href="/assets/js/101.36b1a9cd.js"><link rel="prefetch" href="/assets/js/102.ab6aaef1.js"><link rel="prefetch" href="/assets/js/103.56b65027.js"><link rel="prefetch" href="/assets/js/104.10a9920d.js"><link rel="prefetch" href="/assets/js/105.2af1fce1.js"><link rel="prefetch" href="/assets/js/106.89d909fa.js"><link rel="prefetch" href="/assets/js/107.8a051ba9.js"><link rel="prefetch" href="/assets/js/108.8d32e2bb.js"><link rel="prefetch" href="/assets/js/109.98a9c733.js"><link rel="prefetch" href="/assets/js/11.4f1a38c2.js"><link rel="prefetch" href="/assets/js/110.cb2819bf.js"><link rel="prefetch" href="/assets/js/111.3763e438.js"><link rel="prefetch" href="/assets/js/112.437502fc.js"><link rel="prefetch" href="/assets/js/113.c84b80e9.js"><link rel="prefetch" href="/assets/js/114.e8265ab7.js"><link rel="prefetch" href="/assets/js/115.5950f39b.js"><link rel="prefetch" href="/assets/js/116.7082589d.js"><link rel="prefetch" href="/assets/js/117.9ab33002.js"><link rel="prefetch" href="/assets/js/118.b03051ef.js"><link rel="prefetch" href="/assets/js/119.31fe4216.js"><link rel="prefetch" href="/assets/js/12.397d3f87.js"><link rel="prefetch" href="/assets/js/120.4d52fd08.js"><link rel="prefetch" href="/assets/js/121.024a68dc.js"><link rel="prefetch" href="/assets/js/122.75cd9e9a.js"><link rel="prefetch" href="/assets/js/123.3060f162.js"><link rel="prefetch" href="/assets/js/124.b65e3f9b.js"><link rel="prefetch" href="/assets/js/125.87d06856.js"><link rel="prefetch" href="/assets/js/126.23d0d6ec.js"><link rel="prefetch" href="/assets/js/127.1ff7063e.js"><link rel="prefetch" href="/assets/js/128.e7a78683.js"><link rel="prefetch" href="/assets/js/129.3a378a54.js"><link rel="prefetch" href="/assets/js/13.d1346059.js"><link rel="prefetch" href="/assets/js/130.3820ccc0.js"><link rel="prefetch" href="/assets/js/14.961feb61.js"><link rel="prefetch" href="/assets/js/15.61355499.js"><link rel="prefetch" href="/assets/js/16.6759c278.js"><link rel="prefetch" href="/assets/js/17.39315298.js"><link rel="prefetch" href="/assets/js/18.9995ddc3.js"><link rel="prefetch" href="/assets/js/19.e7007f1f.js"><link rel="prefetch" href="/assets/js/21.42efcf40.js"><link rel="prefetch" href="/assets/js/22.ce83188a.js"><link rel="prefetch" href="/assets/js/23.125b374b.js"><link rel="prefetch" href="/assets/js/24.9a24b2f6.js"><link rel="prefetch" href="/assets/js/25.61d7e926.js"><link rel="prefetch" href="/assets/js/26.4c271fce.js"><link rel="prefetch" href="/assets/js/27.08314644.js"><link rel="prefetch" href="/assets/js/28.44a30857.js"><link rel="prefetch" href="/assets/js/29.4b86327a.js"><link rel="prefetch" href="/assets/js/30.284e1438.js"><link rel="prefetch" href="/assets/js/31.c7fb218e.js"><link rel="prefetch" href="/assets/js/32.9591edea.js"><link rel="prefetch" href="/assets/js/33.52d0ee09.js"><link rel="prefetch" href="/assets/js/34.24dce9bc.js"><link rel="prefetch" href="/assets/js/35.e9e59a19.js"><link rel="prefetch" href="/assets/js/36.470d3b70.js"><link rel="prefetch" href="/assets/js/37.f43d4d57.js"><link rel="prefetch" href="/assets/js/38.bb14e7a9.js"><link rel="prefetch" href="/assets/js/39.4238fcd3.js"><link rel="prefetch" href="/assets/js/4.10111819.js"><link rel="prefetch" href="/assets/js/40.eb5830d8.js"><link rel="prefetch" href="/assets/js/41.f2de0dd7.js"><link rel="prefetch" href="/assets/js/42.ee6bc670.js"><link rel="prefetch" href="/assets/js/43.aeb80fc2.js"><link rel="prefetch" href="/assets/js/44.3dcf73d7.js"><link rel="prefetch" href="/assets/js/45.f60dd2b7.js"><link rel="prefetch" href="/assets/js/46.3ffd9a49.js"><link rel="prefetch" href="/assets/js/47.0629cfd8.js"><link rel="prefetch" href="/assets/js/48.4064d363.js"><link rel="prefetch" href="/assets/js/49.e5cd2868.js"><link rel="prefetch" href="/assets/js/5.bbaa5544.js"><link rel="prefetch" href="/assets/js/50.e1524d44.js"><link rel="prefetch" href="/assets/js/51.ef5d60b4.js"><link rel="prefetch" href="/assets/js/52.9e15bbc1.js"><link rel="prefetch" href="/assets/js/53.9e53a9b3.js"><link rel="prefetch" href="/assets/js/54.bda58726.js"><link rel="prefetch" href="/assets/js/55.cdc29215.js"><link rel="prefetch" href="/assets/js/56.3f0607d3.js"><link rel="prefetch" href="/assets/js/57.b45ba0fb.js"><link rel="prefetch" href="/assets/js/58.12450427.js"><link rel="prefetch" href="/assets/js/59.33096dcc.js"><link rel="prefetch" href="/assets/js/6.8df5fb44.js"><link rel="prefetch" href="/assets/js/60.98645e3a.js"><link rel="prefetch" href="/assets/js/61.413d9151.js"><link rel="prefetch" href="/assets/js/62.cc3b9f5a.js"><link rel="prefetch" href="/assets/js/63.05784f29.js"><link rel="prefetch" href="/assets/js/64.d6d2548e.js"><link rel="prefetch" href="/assets/js/65.dfa3ba68.js"><link rel="prefetch" href="/assets/js/66.bb4f5fde.js"><link rel="prefetch" href="/assets/js/67.2c282a4f.js"><link rel="prefetch" href="/assets/js/68.ce435a87.js"><link rel="prefetch" href="/assets/js/69.e439f6e2.js"><link rel="prefetch" href="/assets/js/7.751d2655.js"><link rel="prefetch" href="/assets/js/70.270cc6b6.js"><link rel="prefetch" href="/assets/js/71.ad1e4a0b.js"><link rel="prefetch" href="/assets/js/72.0adf2b53.js"><link rel="prefetch" href="/assets/js/73.72e019b5.js"><link rel="prefetch" href="/assets/js/74.a4eb5a17.js"><link rel="prefetch" href="/assets/js/75.6412ff6f.js"><link rel="prefetch" href="/assets/js/76.7f462fc1.js"><link rel="prefetch" href="/assets/js/77.16502231.js"><link rel="prefetch" href="/assets/js/78.3082b00c.js"><link rel="prefetch" href="/assets/js/79.4f375500.js"><link rel="prefetch" href="/assets/js/8.6c3fab20.js"><link rel="prefetch" href="/assets/js/80.0f2472d6.js"><link rel="prefetch" href="/assets/js/81.136b6c89.js"><link rel="prefetch" href="/assets/js/82.6f5b7de7.js"><link rel="prefetch" href="/assets/js/83.0eb8579b.js"><link rel="prefetch" href="/assets/js/84.b50a036d.js"><link rel="prefetch" href="/assets/js/85.e7b43c1a.js"><link rel="prefetch" href="/assets/js/86.0cbd7e7b.js"><link rel="prefetch" href="/assets/js/87.647fd8a9.js"><link rel="prefetch" href="/assets/js/88.be268039.js"><link rel="prefetch" href="/assets/js/89.2c0b397f.js"><link rel="prefetch" href="/assets/js/9.ace3bd0d.js"><link rel="prefetch" href="/assets/js/90.fb93a187.js"><link rel="prefetch" href="/assets/js/91.45160178.js"><link rel="prefetch" href="/assets/js/92.4e47d015.js"><link rel="prefetch" href="/assets/js/93.2f9bae72.js"><link rel="prefetch" href="/assets/js/94.c68d9319.js"><link rel="prefetch" href="/assets/js/95.a6932cad.js"><link rel="prefetch" href="/assets/js/96.dea31892.js"><link rel="prefetch" href="/assets/js/97.e8c73484.js"><link rel="prefetch" href="/assets/js/98.bf38dbf7.js"><link rel="prefetch" href="/assets/js/99.edd450af.js">
    <link rel="stylesheet" href="/assets/css/0.styles.f7444686.css">
  </head>
  <body>
    <div id="app" data-server-rendered="true"><div class="theme-container no-sidebar" data-v-6f8f7dda><div data-v-6f8f7dda><div class="password-shadow password-wrapper-out" style="display:none;" data-v-f68096de data-v-6f8f7dda data-v-6f8f7dda><h3 class="title" data-v-f68096de>江流</h3> <p class="description" data-v-f68096de>我的知识存储空间，不大不小刚刚好！</p> <label id="box" class="inputBox" data-v-f68096de><input type="password" value="" data-v-f68096de> <span data-v-f68096de>Konck! Knock!</span> <button data-v-f68096de>OK</button></label> <div class="footer" data-v-f68096de><span data-v-f68096de><i class="iconfont reco-theme" data-v-f68096de></i> <a target="blank" href="https://vuepress-theme-reco.recoluan.com" data-v-f68096de>vuePress-theme-reco</a></span> <span data-v-f68096de><i class="iconfont reco-copyright" data-v-f68096de></i> <a data-v-f68096de><span data-v-f68096de>江流</span>
          
        <span data-v-f68096de>2018 - </span>
        2023
      </a></span></div></div> <div class="hide" data-v-6f8f7dda><header class="navbar" data-v-6f8f7dda><div class="sidebar-button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" role="img" viewBox="0 0 448 512" class="icon"><path fill="currentColor" d="M436 124H12c-6.627 0-12-5.373-12-12V80c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12zm0 160H12c-6.627 0-12-5.373-12-12v-32c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12zm0 160H12c-6.627 0-12-5.373-12-12v-32c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12z"></path></svg></div> <a href="/" class="home-link router-link-active"><img src="/logo.png" alt="江流" class="logo"> <span class="site-name">江流</span></a> <div class="links"><div class="color-picker"><a class="color-button"><i class="iconfont reco-color"></i></a> <div class="color-picker-menu" style="display:none;"><div class="mode-options"><h4 class="title">Choose mode</h4> <ul class="color-mode-options"><li class="dark">dark</li><li class="auto active">auto</li><li class="light">light</li></ul></div></div></div> <div class="search-box"><i class="iconfont reco-search"></i> <input aria-label="Search" autocomplete="off" spellcheck="false" value=""> <!----></div> <nav class="nav-links can-hide"><div class="nav-item"><a href="/" class="nav-link"><i class="iconfont reco-home"></i>
  首页
</a></div><div class="nav-item"><div class="dropdown-wrapper"><a class="dropdown-title"><span class="title"><i class="iconfont reco-category"></i>
      分类
    </span> <span class="arrow right"></span></a> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><!----> <a href="/categories/复盘/" class="nav-link"><i class="undefined"></i>
  复盘
</a></li><li class="dropdown-item"><!----> <a href="/categories/学习总结/" class="nav-link"><i class="undefined"></i>
  学习总结
</a></li><li class="dropdown-item"><!----> <a href="/categories/踩坑/" class="nav-link"><i class="undefined"></i>
  踩坑
</a></li><li class="dropdown-item"><!----> <a href="/categories/工具/" class="nav-link"><i class="undefined"></i>
  工具
</a></li><li class="dropdown-item"><!----> <a href="/categories/Linux/" class="nav-link"><i class="undefined"></i>
  Linux
</a></li><li class="dropdown-item"><!----> <a href="/categories/算法/" class="nav-link"><i class="undefined"></i>
  算法
</a></li><li class="dropdown-item"><!----> <a href="/categories/Java基础/" class="nav-link"><i class="undefined"></i>
  Java基础
</a></li><li class="dropdown-item"><!----> <a href="/categories/高并发编程/" class="nav-link"><i class="undefined"></i>
  高并发编程
</a></li><li class="dropdown-item"><!----> <a href="/categories/数据库/" class="nav-link"><i class="undefined"></i>
  数据库
</a></li><li class="dropdown-item"><!----> <a href="/categories/Java框架/" class="nav-link"><i class="undefined"></i>
  Java框架
</a></li><li class="dropdown-item"><!----> <a href="/categories/学习笔记/" class="nav-link"><i class="undefined"></i>
  学习笔记
</a></li><li class="dropdown-item"><!----> <a href="/categories/框架学习/" class="nav-link"><i class="undefined"></i>
  框架学习
</a></li><li class="dropdown-item"><!----> <a href="/categories/Java项目/" class="nav-link"><i class="undefined"></i>
  Java项目
</a></li></ul></div></div><div class="nav-item"><a href="/tag/" class="nav-link"><i class="iconfont reco-tag"></i>
  标签
</a></div><div class="nav-item"><a href="/timeline/" class="nav-link"><i class="iconfont reco-date"></i>
  时间轴
</a></div><div class="nav-item"><div class="dropdown-wrapper"><a class="dropdown-title"><span class="title"><i class="iconfont reco-note"></i>
      学习笔记
    </span> <span class="arrow right"></span></a> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><!----> <a href="/docs/major-notes/java/" class="nav-link"><i class="undefined"></i>
  Java笔记整理
</a></li><li class="dropdown-item"><!----> <a href="/docs/major-notes/juc/" class="nav-link"><i class="undefined"></i>
  JUC学习笔记
</a></li><li class="dropdown-item"><!----> <a href="/docs/more-notes/jvm.html" class="nav-link"><i class="undefined"></i>
  JVM核心知识
</a></li><li class="dropdown-item"><!----> <a href="/docs/more-notes/vue.html" class="nav-link"><i class="undefined"></i>
  Vue入门笔记
</a></li><li class="dropdown-item"><!----> <a href="/docs/major-notes/linux/" class="nav-link"><i class="undefined"></i>
  Linux笔记整理
</a></li><li class="dropdown-item"><!----> <a href="/docs/major-notes/redis/" class="nav-link"><i class="undefined"></i>
  Redis学习笔记
</a></li><li class="dropdown-item"><!----> <a href="/docs/major-notes/springcloud/" class="nav-link"><i class="undefined"></i>
  SpringCloud笔记
</a></li><li class="dropdown-item"><!----> <a href="/docs/major-notes/spring/" class="nav-link"><i class="undefined"></i>
  Spring学习笔记
</a></li><li class="dropdown-item"><!----> <a href="/docs/more-notes/shiro.html" class="nav-link"><i class="undefined"></i>
  Shiro学习笔记
</a></li><li class="dropdown-item"><!----> <a href="/docs/android-notes/" class="nav-link"><i class="undefined"></i>
  Android学习笔记
</a></li><li class="dropdown-item"><!----> <a href="/docs/project-notes/" class="nav-link"><i class="undefined"></i>
  项目笔记
</a></li></ul></div></div><div class="nav-item"><a href="/docs/collections/" class="nav-link"><i class="iconfont reco-collection"></i>
  收藏夹
</a></div><div class="nav-item"><a href="/docs/life-logs/" class="nav-link"><i class="iconfont reco-camera"></i>
  生活日志
</a></div><div class="nav-item"><div class="dropdown-wrapper"><a class="dropdown-title"><span class="title"><i class="iconfont reco-browse"></i>
      常用网站
    </span> <span class="arrow right"></span></a> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><!----> <a href="http://www.cxysite.com/" target="_blank" rel="noopener noreferrer" class="nav-link external"><i class="undefined"></i>
  程序员导航
  <span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></li><li class="dropdown-item"><!----> <a href="https://www.nowcoder.com/" target="_blank" rel="noopener noreferrer" class="nav-link external"><i class="undefined"></i>
  牛客网
  <span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></li><li class="dropdown-item"><!----> <a href="https://leetcode-cn.com/" target="_blank" rel="noopener noreferrer" class="nav-link external"><i class="undefined"></i>
  力扣
  <span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></li></ul></div></div><div class="nav-item"><div class="dropdown-wrapper"><a class="dropdown-title"><span class="title"><i class="iconfont reco-person"></i>
      私藏博客
    </span> <span class="arrow right"></span></a> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><!----> <a href="https://docker.easydoc.net" target="_blank" rel="noopener noreferrer" class="nav-link external"><i class="undefined"></i>
  快速入门docker
  <span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></li><li class="dropdown-item"><!----> <a href="https://www.nowcoder.com/" target="_blank" rel="noopener noreferrer" class="nav-link external"><i class="undefined"></i>
  牛客网
  <span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></li><li class="dropdown-item"><!----> <a href="https://leetcode-cn.com/" target="_blank" rel="noopener noreferrer" class="nav-link external"><i class="undefined"></i>
  力扣
  <span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></li></ul></div></div><div class="nav-item"><div class="dropdown-wrapper"><a class="dropdown-title"><span class="title"><i class="iconfont reco-message"></i>
      联系方式
    </span> <span class="arrow right"></span></a> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><!----> <a href="https://gitee.com/" target="_blank" rel="noopener noreferrer" class="nav-link external"><i class="iconfont reco-gitee"></i>
  Gitee
  <span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></li><li class="dropdown-item"><!----> <a href="https://github.com/" target="_blank" rel="noopener noreferrer" class="nav-link external"><i class="iconfont reco-github"></i>
  GitHub
  <span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></li></ul></div></div> <!----></nav></div></header> <div class="sidebar-mask" data-v-6f8f7dda></div> <aside class="sidebar" data-v-6f8f7dda><div class="personal-info-wrapper" data-v-cc06b9e8 data-v-6f8f7dda><img src="/avatar.png" alt="author-avatar" class="personal-img" data-v-cc06b9e8> <h3 class="name" data-v-cc06b9e8>
    江流
  </h3> <div class="num" data-v-cc06b9e8><div data-v-cc06b9e8><h3 data-v-cc06b9e8>104</h3> <h6 data-v-cc06b9e8>Articles</h6></div> <div data-v-cc06b9e8><h3 data-v-cc06b9e8>21</h3> <h6 data-v-cc06b9e8>Tags</h6></div></div> <ul class="social-links" data-v-cc06b9e8></ul> <hr data-v-cc06b9e8></div> <nav class="nav-links"><div class="nav-item"><a href="/" class="nav-link"><i class="iconfont reco-home"></i>
  首页
</a></div><div class="nav-item"><div class="dropdown-wrapper"><a class="dropdown-title"><span class="title"><i class="iconfont reco-category"></i>
      分类
    </span> <span class="arrow right"></span></a> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><!----> <a href="/categories/复盘/" class="nav-link"><i class="undefined"></i>
  复盘
</a></li><li class="dropdown-item"><!----> <a href="/categories/学习总结/" class="nav-link"><i class="undefined"></i>
  学习总结
</a></li><li class="dropdown-item"><!----> <a href="/categories/踩坑/" class="nav-link"><i class="undefined"></i>
  踩坑
</a></li><li class="dropdown-item"><!----> <a href="/categories/工具/" class="nav-link"><i class="undefined"></i>
  工具
</a></li><li class="dropdown-item"><!----> <a href="/categories/Linux/" class="nav-link"><i class="undefined"></i>
  Linux
</a></li><li class="dropdown-item"><!----> <a href="/categories/算法/" class="nav-link"><i class="undefined"></i>
  算法
</a></li><li class="dropdown-item"><!----> <a href="/categories/Java基础/" class="nav-link"><i class="undefined"></i>
  Java基础
</a></li><li class="dropdown-item"><!----> <a href="/categories/高并发编程/" class="nav-link"><i class="undefined"></i>
  高并发编程
</a></li><li class="dropdown-item"><!----> <a href="/categories/数据库/" class="nav-link"><i class="undefined"></i>
  数据库
</a></li><li class="dropdown-item"><!----> <a href="/categories/Java框架/" class="nav-link"><i class="undefined"></i>
  Java框架
</a></li><li class="dropdown-item"><!----> <a href="/categories/学习笔记/" class="nav-link"><i class="undefined"></i>
  学习笔记
</a></li><li class="dropdown-item"><!----> <a href="/categories/框架学习/" class="nav-link"><i class="undefined"></i>
  框架学习
</a></li><li class="dropdown-item"><!----> <a href="/categories/Java项目/" class="nav-link"><i class="undefined"></i>
  Java项目
</a></li></ul></div></div><div class="nav-item"><a href="/tag/" class="nav-link"><i class="iconfont reco-tag"></i>
  标签
</a></div><div class="nav-item"><a href="/timeline/" class="nav-link"><i class="iconfont reco-date"></i>
  时间轴
</a></div><div class="nav-item"><div class="dropdown-wrapper"><a class="dropdown-title"><span class="title"><i class="iconfont reco-note"></i>
      学习笔记
    </span> <span class="arrow right"></span></a> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><!----> <a href="/docs/major-notes/java/" class="nav-link"><i class="undefined"></i>
  Java笔记整理
</a></li><li class="dropdown-item"><!----> <a href="/docs/major-notes/juc/" class="nav-link"><i class="undefined"></i>
  JUC学习笔记
</a></li><li class="dropdown-item"><!----> <a href="/docs/more-notes/jvm.html" class="nav-link"><i class="undefined"></i>
  JVM核心知识
</a></li><li class="dropdown-item"><!----> <a href="/docs/more-notes/vue.html" class="nav-link"><i class="undefined"></i>
  Vue入门笔记
</a></li><li class="dropdown-item"><!----> <a href="/docs/major-notes/linux/" class="nav-link"><i class="undefined"></i>
  Linux笔记整理
</a></li><li class="dropdown-item"><!----> <a href="/docs/major-notes/redis/" class="nav-link"><i class="undefined"></i>
  Redis学习笔记
</a></li><li class="dropdown-item"><!----> <a href="/docs/major-notes/springcloud/" class="nav-link"><i class="undefined"></i>
  SpringCloud笔记
</a></li><li class="dropdown-item"><!----> <a href="/docs/major-notes/spring/" class="nav-link"><i class="undefined"></i>
  Spring学习笔记
</a></li><li class="dropdown-item"><!----> <a href="/docs/more-notes/shiro.html" class="nav-link"><i class="undefined"></i>
  Shiro学习笔记
</a></li><li class="dropdown-item"><!----> <a href="/docs/android-notes/" class="nav-link"><i class="undefined"></i>
  Android学习笔记
</a></li><li class="dropdown-item"><!----> <a href="/docs/project-notes/" class="nav-link"><i class="undefined"></i>
  项目笔记
</a></li></ul></div></div><div class="nav-item"><a href="/docs/collections/" class="nav-link"><i class="iconfont reco-collection"></i>
  收藏夹
</a></div><div class="nav-item"><a href="/docs/life-logs/" class="nav-link"><i class="iconfont reco-camera"></i>
  生活日志
</a></div><div class="nav-item"><div class="dropdown-wrapper"><a class="dropdown-title"><span class="title"><i class="iconfont reco-browse"></i>
      常用网站
    </span> <span class="arrow right"></span></a> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><!----> <a href="http://www.cxysite.com/" target="_blank" rel="noopener noreferrer" class="nav-link external"><i class="undefined"></i>
  程序员导航
  <span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></li><li class="dropdown-item"><!----> <a href="https://www.nowcoder.com/" target="_blank" rel="noopener noreferrer" class="nav-link external"><i class="undefined"></i>
  牛客网
  <span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></li><li class="dropdown-item"><!----> <a href="https://leetcode-cn.com/" target="_blank" rel="noopener noreferrer" class="nav-link external"><i class="undefined"></i>
  力扣
  <span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></li></ul></div></div><div class="nav-item"><div class="dropdown-wrapper"><a class="dropdown-title"><span class="title"><i class="iconfont reco-person"></i>
      私藏博客
    </span> <span class="arrow right"></span></a> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><!----> <a href="https://docker.easydoc.net" target="_blank" rel="noopener noreferrer" class="nav-link external"><i class="undefined"></i>
  快速入门docker
  <span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></li><li class="dropdown-item"><!----> <a href="https://www.nowcoder.com/" target="_blank" rel="noopener noreferrer" class="nav-link external"><i class="undefined"></i>
  牛客网
  <span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></li><li class="dropdown-item"><!----> <a href="https://leetcode-cn.com/" target="_blank" rel="noopener noreferrer" class="nav-link external"><i class="undefined"></i>
  力扣
  <span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></li></ul></div></div><div class="nav-item"><div class="dropdown-wrapper"><a class="dropdown-title"><span class="title"><i class="iconfont reco-message"></i>
      联系方式
    </span> <span class="arrow right"></span></a> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><!----> <a href="https://gitee.com/" target="_blank" rel="noopener noreferrer" class="nav-link external"><i class="iconfont reco-gitee"></i>
  Gitee
  <span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></li><li class="dropdown-item"><!----> <a href="https://github.com/" target="_blank" rel="noopener noreferrer" class="nav-link external"><i class="iconfont reco-github"></i>
  GitHub
  <span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></li></ul></div></div> <!----></nav> <!----> </aside> <div class="password-shadow password-wrapper-in" style="display:none;" data-v-f68096de data-v-6f8f7dda><h3 class="title" data-v-f68096de>Android消息机制解析</h3> <!----> <label id="box" class="inputBox" data-v-f68096de><input type="password" value="" data-v-f68096de> <span data-v-f68096de>Konck! Knock!</span> <button data-v-f68096de>OK</button></label> <div class="footer" data-v-f68096de><span data-v-f68096de><i class="iconfont reco-theme" data-v-f68096de></i> <a target="blank" href="https://vuepress-theme-reco.recoluan.com" data-v-f68096de>vuePress-theme-reco</a></span> <span data-v-f68096de><i class="iconfont reco-copyright" data-v-f68096de></i> <a data-v-f68096de><span data-v-f68096de>江流</span>
          
        <span data-v-f68096de>2018 - </span>
        2023
      </a></span></div></div> <div data-v-6f8f7dda><div data-v-6f8f7dda><main class="page"><section style="display:;"><div class="page-title"><h1 class="title">Android消息机制解析</h1> <div data-v-1e62957f><i class="iconfont reco-account" data-v-1e62957f><span data-v-1e62957f>江流</span></i> <i class="iconfont reco-date" data-v-1e62957f><span data-v-1e62957f>8/1/2022</span></i> <!----> <i class="tags iconfont reco-tag" data-v-1e62957f><span class="tag-item" data-v-1e62957f>Android</span></i></div></div> <div class="theme-reco-content content__default"><h3 id="为什么主线程中可以直接使用handler"><a href="#为什么主线程中可以直接使用handler" class="header-anchor">#</a> 为什么主线程中可以直接使用Handler?</h3> <p>Handler 的运行需要底层的 MessageQueue 和 Looper 支撑，MessageQueue 是以单链表为数据结构的消息列表，Looper 以无限循环的形式去查找 MessageQueue 中是否有新消息需要处理。Looper 中还有一个特殊概念 ThreadLocal，可以在不同的线程中互补干扰地存储并提供数据，通过 ThreadLocal 可以轻松获取每个线程的 Looper。线程默认没有 Looper，如果需要使用 Handler 就必须为线程创建 Looper。而主线程，也就是 ActivityThread，它在创建时会初始化 Looper，这就是在主线程中默认可以使用 Handler 的原因。</p> <h3 id="为什么android会提供handler"><a href="#为什么android会提供handler" class="header-anchor">#</a> 为什么Android会提供Handler?</h3> <p>Android 规定访问 UI 只能在主线程中进行，如果子线程中访问 UI，那么程序就会抛出异常。ViewRootImpl 对 UI 操作做了验证，该验证过程是由 checkThread 方法完成的：</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">void</span> <span class="token function">checkThread</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
    <span class="token keyword">if</span><span class="token punctuation">(</span>mThread <span class="token operator">!=</span> <span class="token class-name">Thread</span><span class="token punctuation">.</span>currentThrad<span class="token punctuation">)</span><span class="token punctuation">{</span>
        <span class="token keyword">throw</span> <span class="token keyword">new</span> <span class="token class-name">CalledFromWrongThreadException</span><span class="token punctuation">(</span>
        <span class="token string">&quot;Only the original thread that crated a view hierarchy can touch its views&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br></div></div><p>同时 Android 又建议在主线程中不要进行耗时操作，否则导致程序无法响应即 ANR。而在系统提供 Handler，正是为了解决子线程中无法访问 UI 的矛盾。</p> <h3 id="为什么不允许子线程中访问ui呢"><a href="#为什么不允许子线程中访问ui呢" class="header-anchor">#</a> 为什么不允许子线程中访问UI呢？</h3> <p>这是因为 Android 的 UI 控件时线程不安全的，如果多线程中并发访问可能导致 UI 控件处于不可预期的状态。</p> <h3 id="为什么系统不对ui的访问加上锁机制呢"><a href="#为什么系统不对ui的访问加上锁机制呢" class="header-anchor">#</a> 为什么系统不对UI的访问加上锁机制呢？</h3> <p>首先加上锁机制会让 UI 访问逻辑变得负责，其次锁机制会降低 UI 的访问效率，阻塞某些线程的执行。鉴于以上两个缺点，最简单且高效的方法就是采用单线程模型来处理 UI 组件。</p> <h3 id="handler的处理过程"><a href="#handler的处理过程" class="header-anchor">#</a> Handler的处理过程</h3> <p>Handler 创建完毕后，内部的 Looper 及 MessageQueue 就可以和 Handler 一起协同工作。通过 Handler 的 post 方法将一个 Runnable 投递到 Handler 内部的 Looper 中去处理，也可以通过 Handler 的 send 方法发送一个消息，该消息同样会在 Looper 中处理。而 post 方法最终也是通过 send 方法来完成的。</p> <p>当 Handler 的 send 方法调用时，会调用 MessageQueue 的 enqueueMessage 方法将这个消息放到消息队列中，然后 Looper 发现有消息来时就会处理这个消息，最终消息中的 Runable 或 Handler 的 HandlerMessage 方法就会被调用。而 Looper 是运行在 Handler 所在线程中，这样一来 Handler 中的业务就被切换到创建 Handler 所在的线程中去执行了。</p> <p><img src="http://images.xbnote.top/images/202208131628253.png" alt="未命名文件"></p> <h3 id="threadlocal-java8"><a href="#threadlocal-java8" class="header-anchor">#</a> ThreadLocal (Java8)</h3> <h4 id="运用场景"><a href="#运用场景" class="header-anchor">#</a> 运用场景</h4> <ol><li>存储当前线程的数据</li> <li>复杂逻辑下的对象传递</li></ol> <h4 id="内部原理"><a href="#内部原理" class="header-anchor">#</a> 内部原理</h4> <p>ThreadLocal 是一个泛型类，其定义为 public class ThreadLocal<T> ，所以弄清楚 ThreadLocal 的 get 和 set 方法就可以明白其工作原理。</T></p> <p>先看 set 方法：</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code> <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">set</span><span class="token punctuation">(</span><span class="token class-name">T</span> value<span class="token punctuation">)</span> <span class="token punctuation">{</span>
     <span class="token comment">//1、获取当前线程</span>
     <span class="token class-name">Thread</span> t <span class="token operator">=</span> <span class="token class-name">Thread</span><span class="token punctuation">.</span><span class="token function">currentThread</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
     <span class="token comment">//2、获取线程中的属性 threadLocalMap ,如果threadLocalMap 不为空，</span>
     <span class="token comment">//则直接更新要保存的变量值，否则创建threadLocalMap，并赋值</span>
     <span class="token class-name">ThreadLocalMap</span> map <span class="token operator">=</span> <span class="token function">getMap</span><span class="token punctuation">(</span>t<span class="token punctuation">)</span><span class="token punctuation">;</span>
     <span class="token keyword">if</span> <span class="token punctuation">(</span>map <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span>
         map<span class="token punctuation">.</span><span class="token function">set</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">,</span> value<span class="token punctuation">)</span><span class="token punctuation">;</span>
     <span class="token keyword">else</span>
         <span class="token comment">// 初始化thradLocalMap 并赋值</span>
         <span class="token function">createMap</span><span class="token punctuation">(</span>t<span class="token punctuation">,</span> value<span class="token punctuation">)</span><span class="token punctuation">;</span>
 <span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br></div></div><p>ThreadLocalMap 是 ThreadLocal 的内部静态类，而它的构成主要是用 Entry 来保存数据 ，而且还是继承的弱引用。在 Entry 内部使用 ThreadLocal 作为 key，使用我们设置的 value 作为 value。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">static</span> <span class="token keyword">class</span> <span class="token class-name">ThreadLocalMap</span> <span class="token punctuation">{</span>
 <span class="token comment">/**
   * The entries in this hash map extend WeakReference, using
   * its main ref field as the key (which is always a
   * ThreadLocal object).  Note that null keys (i.e. entry.get()
   * == null) mean that the key is no longer referenced, so the
   * entry can be expunged from table.  Such entries are referred to
   * as &quot;stale entries&quot; in the code that follows.
   */</span>
    <span class="token keyword">static</span> <span class="token keyword">class</span> <span class="token class-name">Entry</span> <span class="token keyword">extends</span> <span class="token class-name">WeakReference</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">ThreadLocal</span><span class="token punctuation">&lt;</span><span class="token operator">?</span><span class="token punctuation">&gt;</span><span class="token punctuation">&gt;</span></span> <span class="token punctuation">{</span>
        <span class="token comment">/** The value associated with this ThreadLocal. */</span>
        <span class="token class-name">Object</span> value<span class="token punctuation">;</span>
        <span class="token class-name">Entry</span><span class="token punctuation">(</span><span class="token class-name">ThreadLocal</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token operator">?</span><span class="token punctuation">&gt;</span></span> k<span class="token punctuation">,</span> <span class="token class-name">Object</span> v<span class="token punctuation">)</span> <span class="token punctuation">{</span>
            <span class="token keyword">super</span><span class="token punctuation">(</span>k<span class="token punctuation">)</span><span class="token punctuation">;</span>
            value <span class="token operator">=</span> v<span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br><span class="line-number">16</span><br><span class="line-number">17</span><br><span class="line-number">18</span><br></div></div><div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token comment">//这个是threadlocal 的内部方法</span>
<span class="token keyword">void</span> <span class="token function">createMap</span><span class="token punctuation">(</span><span class="token class-name">Thread</span> t<span class="token punctuation">,</span> <span class="token class-name">T</span> firstValue<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        t<span class="token punctuation">.</span>threadLocals <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ThreadLocalMap</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">,</span> firstValue<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
 
<span class="token comment">//ThreadLocalMap 构造方法</span>
<span class="token class-name">ThreadLocalMap</span><span class="token punctuation">(</span><span class="token class-name">ThreadLocal</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token operator">?</span><span class="token punctuation">&gt;</span></span> firstKey<span class="token punctuation">,</span> <span class="token class-name">Object</span> firstValue<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    table <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Entry</span><span class="token punctuation">[</span><span class="token constant">INITIAL_CAPACITY</span><span class="token punctuation">]</span><span class="token punctuation">;</span>
    <span class="token keyword">int</span> i <span class="token operator">=</span> firstKey<span class="token punctuation">.</span>threadLocalHashCode <span class="token operator">&amp;</span> <span class="token punctuation">(</span><span class="token constant">INITIAL_CAPACITY</span> <span class="token operator">-</span> <span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    table<span class="token punctuation">[</span>i<span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Entry</span><span class="token punctuation">(</span>firstKey<span class="token punctuation">,</span> firstValue<span class="token punctuation">)</span><span class="token punctuation">;</span>
    size <span class="token operator">=</span> <span class="token number">1</span><span class="token punctuation">;</span>
    <span class="token function">setThreshold</span><span class="token punctuation">(</span><span class="token constant">INITIAL_CAPACITY</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br></div></div><p>ThreadLocalMap 其实是 Thread 线程的一个属性值，而 ThreadLocal 是维护 ThreadLocalMap。ThreadLocal 的 get 方法如下：</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">public</span> <span class="token class-name">T</span> <span class="token function">get</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token comment">//1、获取当前线程</span>
    <span class="token class-name">Thread</span> t <span class="token operator">=</span> <span class="token class-name">Thread</span><span class="token punctuation">.</span><span class="token function">currentThread</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token comment">//2、获取当前线程的ThreadLocalMap</span>
    <span class="token class-name">ThreadLocalMap</span> map <span class="token operator">=</span> <span class="token function">getMap</span><span class="token punctuation">(</span>t<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token comment">//3、如果map数据为空，</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span>map <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token comment">//3.1、获取threalLocalMap中存储的值</span>
        <span class="token class-name">ThreadLocalMap<span class="token punctuation">.</span>Entry</span> e <span class="token operator">=</span> map<span class="token punctuation">.</span><span class="token function">getEntry</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>e <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
            <span class="token annotation punctuation">@SuppressWarnings</span><span class="token punctuation">(</span><span class="token string">&quot;unchecked&quot;</span><span class="token punctuation">)</span>
            <span class="token class-name">T</span> result <span class="token operator">=</span> <span class="token punctuation">(</span><span class="token class-name">T</span><span class="token punctuation">)</span>e<span class="token punctuation">.</span>value<span class="token punctuation">;</span>
            <span class="token keyword">return</span> result<span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>
    <span class="token comment">//如果是数据为null，则初始化，初始化的结果，TheralLocalMap中存放key值为threadLocal，值为null</span>
    <span class="token keyword">return</span> <span class="token function">setInitialValue</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>


<span class="token keyword">private</span> <span class="token class-name">T</span> <span class="token function">setInitialValue</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token class-name">T</span> value <span class="token operator">=</span> <span class="token function">initialValue</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token class-name">Thread</span> t <span class="token operator">=</span> <span class="token class-name">Thread</span><span class="token punctuation">.</span><span class="token function">currentThread</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token class-name">ThreadLocalMap</span> map <span class="token operator">=</span> <span class="token function">getMap</span><span class="token punctuation">(</span>t<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span>map <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span>
        map<span class="token punctuation">.</span><span class="token function">set</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">,</span> value<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">else</span>
        <span class="token function">createMap</span><span class="token punctuation">(</span>t<span class="token punctuation">,</span> value<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">return</span> value<span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br><span class="line-number">16</span><br><span class="line-number">17</span><br><span class="line-number">18</span><br><span class="line-number">19</span><br><span class="line-number">20</span><br><span class="line-number">21</span><br><span class="line-number">22</span><br><span class="line-number">23</span><br><span class="line-number">24</span><br><span class="line-number">25</span><br><span class="line-number">26</span><br><span class="line-number">27</span><br><span class="line-number">28</span><br><span class="line-number">29</span><br><span class="line-number">30</span><br></div></div><p>参考博客：<a href="https://blog.csdn.net/u010445301/article/details/111322569" target="_blank" rel="noopener noreferrer">史上最全ThreadLocal 详解（一）<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></p> <h3 id="messagequeue工作原理"><a href="#messagequeue工作原理" class="header-anchor">#</a> MessageQueue工作原理</h3> <p>MessageQueue 组要包含两个操作：插入和读取。读取操作本身伴随着删除操作，插入和读取对应的方法分别为 enqueueMessage 和 next。MessageQueue 是通过一个单链表的数据结构来维护消息列表，在插入和删除上比较有优势。</p> <p>enqueueMessage 源码如下：</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">boolean</span> <span class="token function">enqueueMessage</span><span class="token punctuation">(</span><span class="token class-name">Message</span> msg<span class="token punctuation">,</span> <span class="token keyword">long</span> when<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span>
    <span class="token keyword">synchronized</span> <span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span>
        msg<span class="token punctuation">.</span><span class="token function">markInUse</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        msg<span class="token punctuation">.</span>when <span class="token operator">=</span> when<span class="token punctuation">;</span>
        <span class="token class-name">Message</span> p <span class="token operator">=</span> mMessages<span class="token punctuation">;</span>
        <span class="token keyword">boolean</span> needWake<span class="token punctuation">;</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>p <span class="token operator">==</span> <span class="token keyword">null</span> <span class="token operator">||</span> when <span class="token operator">==</span> <span class="token number">0</span> <span class="token operator">||</span> when <span class="token operator">&lt;</span> p<span class="token punctuation">.</span>when<span class="token punctuation">)</span> <span class="token punctuation">{</span>
            <span class="token comment">// New head, wake up the event queue if blocked.</span>
            msg<span class="token punctuation">.</span>next <span class="token operator">=</span> p<span class="token punctuation">;</span>
            mMessages <span class="token operator">=</span> msg<span class="token punctuation">;</span>
            needWake <span class="token operator">=</span> mBlocked<span class="token punctuation">;</span>
        <span class="token punctuation">}</span> <span class="token keyword">else</span> <span class="token punctuation">{</span>
            <span class="token comment">// Inserted within the middle of the queue.  Usually we don't have to wake</span>
            <span class="token comment">// up the event queue unless there is a barrier at the head of the queue</span>
            <span class="token comment">// and the message is the earliest asynchronous message in the queue.</span>
            needWake <span class="token operator">=</span> mBlocked <span class="token operator">&amp;&amp;</span> p<span class="token punctuation">.</span>target <span class="token operator">==</span> <span class="token keyword">null</span> <span class="token operator">&amp;&amp;</span> msg<span class="token punctuation">.</span><span class="token function">isAsynchronous</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token class-name">Message</span> prev<span class="token punctuation">;</span>
            <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token punctuation">;</span><span class="token punctuation">;</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
                prev <span class="token operator">=</span> p<span class="token punctuation">;</span>
                p <span class="token operator">=</span> p<span class="token punctuation">.</span>next<span class="token punctuation">;</span>
                <span class="token keyword">if</span> <span class="token punctuation">(</span>p <span class="token operator">==</span> <span class="token keyword">null</span> <span class="token operator">||</span> when <span class="token operator">&lt;</span> p<span class="token punctuation">.</span>when<span class="token punctuation">)</span> <span class="token punctuation">{</span>
                    <span class="token keyword">break</span><span class="token punctuation">;</span>
                <span class="token punctuation">}</span>
                <span class="token keyword">if</span> <span class="token punctuation">(</span>needWake <span class="token operator">&amp;&amp;</span> p<span class="token punctuation">.</span><span class="token function">isAsynchronous</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
                    needWake <span class="token operator">=</span> <span class="token boolean">false</span><span class="token punctuation">;</span>
                <span class="token punctuation">}</span>
            <span class="token punctuation">}</span>
            msg<span class="token punctuation">.</span>next <span class="token operator">=</span> p<span class="token punctuation">;</span> <span class="token comment">// invariant: p == prev.next</span>
            prev<span class="token punctuation">.</span>next <span class="token operator">=</span> msg<span class="token punctuation">;</span>
        <span class="token punctuation">}</span>

        <span class="token comment">// We can assume mPtr != 0 because mQuitting is false.</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>needWake<span class="token punctuation">)</span> <span class="token punctuation">{</span>
            <span class="token function">nativeWake</span><span class="token punctuation">(</span>mPtr<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>
    <span class="token keyword">return</span> <span class="token boolean">true</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br><span class="line-number">16</span><br><span class="line-number">17</span><br><span class="line-number">18</span><br><span class="line-number">19</span><br><span class="line-number">20</span><br><span class="line-number">21</span><br><span class="line-number">22</span><br><span class="line-number">23</span><br><span class="line-number">24</span><br><span class="line-number">25</span><br><span class="line-number">26</span><br><span class="line-number">27</span><br><span class="line-number">28</span><br><span class="line-number">29</span><br><span class="line-number">30</span><br><span class="line-number">31</span><br><span class="line-number">32</span><br><span class="line-number">33</span><br><span class="line-number">34</span><br><span class="line-number">35</span><br><span class="line-number">36</span><br><span class="line-number">37</span><br><span class="line-number">38</span><br><span class="line-number">39</span><br><span class="line-number">40</span><br></div></div><p>next 源码如下：</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token class-name">Message</span> <span class="token function">next</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span>
        <span class="token keyword">int</span> pendingIdleHandlerCount <span class="token operator">=</span> <span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">;</span> <span class="token comment">// -1 only during first iteration</span>
        <span class="token keyword">int</span> nextPollTimeoutMillis <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>
        <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token punctuation">;</span><span class="token punctuation">;</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span>nextPollTimeoutMillis <span class="token operator">!=</span> <span class="token number">0</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
                <span class="token class-name">Binder</span><span class="token punctuation">.</span><span class="token function">flushPendingCommands</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">}</span>

            <span class="token function">nativePollOnce</span><span class="token punctuation">(</span>ptr<span class="token punctuation">,</span> nextPollTimeoutMillis<span class="token punctuation">)</span><span class="token punctuation">;</span>

            <span class="token keyword">synchronized</span> <span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
                <span class="token comment">// Try to retrieve the next message.  Return if found.</span>
                <span class="token keyword">final</span> <span class="token keyword">long</span> now <span class="token operator">=</span> <span class="token class-name">SystemClock</span><span class="token punctuation">.</span><span class="token function">uptimeMillis</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token class-name">Message</span> prevMsg <span class="token operator">=</span> <span class="token keyword">null</span><span class="token punctuation">;</span>
                <span class="token class-name">Message</span> msg <span class="token operator">=</span> mMessages<span class="token punctuation">;</span>
                <span class="token keyword">if</span> <span class="token punctuation">(</span>msg <span class="token operator">!=</span> <span class="token keyword">null</span> <span class="token operator">&amp;&amp;</span> msg<span class="token punctuation">.</span>target <span class="token operator">==</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
                    <span class="token comment">// Stalled by a barrier.  Find the next asynchronous message in the queue.</span>
                    <span class="token keyword">do</span> <span class="token punctuation">{</span>
                        prevMsg <span class="token operator">=</span> msg<span class="token punctuation">;</span>
                        msg <span class="token operator">=</span> msg<span class="token punctuation">.</span>next<span class="token punctuation">;</span>
                    <span class="token punctuation">}</span> <span class="token keyword">while</span> <span class="token punctuation">(</span>msg <span class="token operator">!=</span> <span class="token keyword">null</span> <span class="token operator">&amp;&amp;</span> <span class="token operator">!</span>msg<span class="token punctuation">.</span><span class="token function">isAsynchronous</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token punctuation">}</span>
                <span class="token keyword">if</span> <span class="token punctuation">(</span>msg <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
                    <span class="token keyword">if</span> <span class="token punctuation">(</span>now <span class="token operator">&lt;</span> msg<span class="token punctuation">.</span>when<span class="token punctuation">)</span> <span class="token punctuation">{</span>
                        <span class="token comment">// Next message is not ready.  Set a timeout to wake up when it is ready.</span>
                        nextPollTimeoutMillis <span class="token operator">=</span> <span class="token punctuation">(</span><span class="token keyword">int</span><span class="token punctuation">)</span> <span class="token class-name">Math</span><span class="token punctuation">.</span><span class="token function">min</span><span class="token punctuation">(</span>msg<span class="token punctuation">.</span>when <span class="token operator">-</span> now<span class="token punctuation">,</span> <span class="token class-name">Integer</span><span class="token punctuation">.</span><span class="token constant">MAX_VALUE</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token punctuation">}</span> <span class="token keyword">else</span> <span class="token punctuation">{</span>
                        <span class="token comment">// Got a message.</span>
                        mBlocked <span class="token operator">=</span> <span class="token boolean">false</span><span class="token punctuation">;</span>
                        <span class="token keyword">if</span> <span class="token punctuation">(</span>prevMsg <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
                            prevMsg<span class="token punctuation">.</span>next <span class="token operator">=</span> msg<span class="token punctuation">.</span>next<span class="token punctuation">;</span>
                        <span class="token punctuation">}</span> <span class="token keyword">else</span> <span class="token punctuation">{</span>
                            mMessages <span class="token operator">=</span> msg<span class="token punctuation">.</span>next<span class="token punctuation">;</span>
                        <span class="token punctuation">}</span>
                        msg<span class="token punctuation">.</span>next <span class="token operator">=</span> <span class="token keyword">null</span><span class="token punctuation">;</span>
                        <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token constant">DEBUG</span><span class="token punctuation">)</span> <span class="token class-name">Log</span><span class="token punctuation">.</span><span class="token function">v</span><span class="token punctuation">(</span><span class="token constant">TAG</span><span class="token punctuation">,</span> <span class="token string">&quot;Returning message: &quot;</span> <span class="token operator">+</span> msg<span class="token punctuation">)</span><span class="token punctuation">;</span>
                        msg<span class="token punctuation">.</span><span class="token function">markInUse</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                        <span class="token keyword">return</span> msg<span class="token punctuation">;</span>
                    <span class="token punctuation">}</span>
                <span class="token punctuation">}</span> <span class="token keyword">else</span> <span class="token punctuation">{</span>
                    <span class="token comment">// No more messages.</span>
                    nextPollTimeoutMillis <span class="token operator">=</span> <span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">;</span>
                <span class="token punctuation">}</span>
                <span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span>
            <span class="token punctuation">}</span>
            <span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span>
        <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br><span class="line-number">16</span><br><span class="line-number">17</span><br><span class="line-number">18</span><br><span class="line-number">19</span><br><span class="line-number">20</span><br><span class="line-number">21</span><br><span class="line-number">22</span><br><span class="line-number">23</span><br><span class="line-number">24</span><br><span class="line-number">25</span><br><span class="line-number">26</span><br><span class="line-number">27</span><br><span class="line-number">28</span><br><span class="line-number">29</span><br><span class="line-number">30</span><br><span class="line-number">31</span><br><span class="line-number">32</span><br><span class="line-number">33</span><br><span class="line-number">34</span><br><span class="line-number">35</span><br><span class="line-number">36</span><br><span class="line-number">37</span><br><span class="line-number">38</span><br><span class="line-number">39</span><br><span class="line-number">40</span><br><span class="line-number">41</span><br><span class="line-number">42</span><br><span class="line-number">43</span><br><span class="line-number">44</span><br><span class="line-number">45</span><br><span class="line-number">46</span><br><span class="line-number">47</span><br><span class="line-number">48</span><br><span class="line-number">49</span><br></div></div><h3 id="looper工作原理"><a href="#looper工作原理" class="header-anchor">#</a> Looper工作原理</h3> <p>Looper 在 Android 消息机制中扮演着消息循环角色，它会不停从 Message 中查看是否有新消息进行处理，没有则一直阻塞。其构造函数如下：</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">private</span> <span class="token class-name">Looper</span><span class="token punctuation">(</span><span class="token keyword">boolean</span> quitAllowed<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    mQueue <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">MessageQueue</span><span class="token punctuation">(</span>quitAllowed<span class="token punctuation">)</span><span class="token punctuation">;</span>
    mThread <span class="token operator">=</span> <span class="token class-name">Thread</span><span class="token punctuation">.</span><span class="token function">currentThread</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br></div></div><p>Handler 工作需要 Looper，一个线程通过 Looper.prepare() 来创建一个 Looper，接着通过 Looper.loop() 来开启消息循环。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">new</span> <span class="token class-name">Thread</span><span class="token punctuation">(</span><span class="token string">&quot;ThreadName&quot;</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
    <span class="token annotation punctuation">@Override</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">run</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
        <span class="token class-name">Looper</span><span class="token punctuation">.</span><span class="token function">prepare</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">Handler</span> handler <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Handler</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">Looper</span><span class="token punctuation">.</span><span class="token function">looper</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span><span class="token punctuation">.</span><span class="token function">start</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br></div></div><p>Looper 除了 prepare 方法外，还提供了 prepareMainLooper 方法，该方法主要是给 ActivityThread 创建 Looper 使用的，本质也是通过 prepare 来实现的。此外，Looper 还提供了一个 getMainLooper 方法，通过它可以在任何地方获取到主线程的 Looper。Looper 也是可以退出的，它提供了 quit 和 quitSafely 来退出一个 Looper，两者区别在于 quit 会直接退出，而 quickSafely 只是设定一个退出标识，然后把消息队列的已有消息处理完毕后才安全退出。</p> <p>Looper 在调用 loop 方法后，消息循环系统才会真正起作用，其实现如下所示：</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code>    <span class="token comment">/**
     * Run the message queue in this thread. Be sure to call
     * {@link #quit()} to end the loop.
     */</span>
    <span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token keyword">void</span> <span class="token function">loop</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">final</span> <span class="token class-name">Looper</span> me <span class="token operator">=</span> <span class="token function">myLooper</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>me <span class="token operator">==</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
            <span class="token keyword">throw</span> <span class="token keyword">new</span> <span class="token class-name">RuntimeException</span><span class="token punctuation">(</span><span class="token string">&quot;No Looper; Looper.prepare() wasn't called on this thread.&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
        <span class="token keyword">final</span> <span class="token class-name">MessageQueue</span> queue <span class="token operator">=</span> me<span class="token punctuation">.</span>mQueue<span class="token punctuation">;</span> 

        <span class="token comment">// Make sure the identity of this thread is that of the local process,</span>
        <span class="token comment">// and keep track of what that identity token actually is.</span>
        <span class="token class-name">Binder</span><span class="token punctuation">.</span><span class="token function">clearCallingIdentity</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">final</span> <span class="token keyword">long</span> ident <span class="token operator">=</span> <span class="token class-name">Binder</span><span class="token punctuation">.</span><span class="token function">clearCallingIdentity</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token comment">// Allow overriding a threshold with a system prop. e.g.</span>
        <span class="token comment">// adb shell 'setprop log.looper.1000.main.slow 1 &amp;&amp; stop &amp;&amp; start'</span>
        <span class="token keyword">final</span> <span class="token keyword">int</span> thresholdOverride <span class="token operator">=</span>
                <span class="token class-name">SystemProperties</span><span class="token punctuation">.</span><span class="token function">getInt</span><span class="token punctuation">(</span><span class="token string">&quot;log.looper.&quot;</span>
                        <span class="token operator">+</span> <span class="token class-name">Process</span><span class="token punctuation">.</span><span class="token function">myUid</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">+</span> <span class="token string">&quot;.&quot;</span>
                        <span class="token operator">+</span> <span class="token class-name">Thread</span><span class="token punctuation">.</span><span class="token function">currentThread</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getName</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
                        <span class="token operator">+</span> <span class="token string">&quot;.slow&quot;</span><span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token keyword">boolean</span> slowDeliveryDetected <span class="token operator">=</span> <span class="token boolean">false</span><span class="token punctuation">;</span>

        <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token punctuation">;</span><span class="token punctuation">;</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
            <span class="token comment">//queue.next()是一个阻塞方法，没有消息时一直阻塞</span>
            <span class="token class-name">Message</span> msg <span class="token operator">=</span> queue<span class="token punctuation">.</span><span class="token function">next</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token comment">// might block</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span>msg <span class="token operator">==</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
                <span class="token comment">//消息为空时则跳出循环		</span>
                <span class="token keyword">return</span><span class="token punctuation">;</span>
            <span class="token punctuation">}</span>

            <span class="token comment">// This must be in a local variable, in case a UI event sets the logger</span>
            <span class="token keyword">final</span> <span class="token class-name">Printer</span> logging <span class="token operator">=</span> me<span class="token punctuation">.</span>mLogging<span class="token punctuation">;</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span>logging <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
                logging<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">&quot;&gt;&gt;&gt;&gt;&gt; Dispatching to &quot;</span> <span class="token operator">+</span> msg<span class="token punctuation">.</span>target <span class="token operator">+</span> <span class="token string">&quot; &quot;</span> <span class="token operator">+</span>
                        msg<span class="token punctuation">.</span>callback <span class="token operator">+</span> <span class="token string">&quot;: &quot;</span> <span class="token operator">+</span> msg<span class="token punctuation">.</span>what<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">}</span>

            <span class="token keyword">final</span> <span class="token keyword">long</span> traceTag <span class="token operator">=</span> me<span class="token punctuation">.</span>mTraceTag<span class="token punctuation">;</span>
            <span class="token keyword">long</span> slowDispatchThresholdMs <span class="token operator">=</span> me<span class="token punctuation">.</span>mSlowDispatchThresholdMs<span class="token punctuation">;</span>
            <span class="token keyword">long</span> slowDeliveryThresholdMs <span class="token operator">=</span> me<span class="token punctuation">.</span>mSlowDeliveryThresholdMs<span class="token punctuation">;</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span>thresholdOverride <span class="token operator">&gt;</span> <span class="token number">0</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
                slowDispatchThresholdMs <span class="token operator">=</span> thresholdOverride<span class="token punctuation">;</span>
                slowDeliveryThresholdMs <span class="token operator">=</span> thresholdOverride<span class="token punctuation">;</span>
            <span class="token punctuation">}</span>
            <span class="token keyword">final</span> <span class="token keyword">boolean</span> logSlowDelivery <span class="token operator">=</span> <span class="token punctuation">(</span>slowDeliveryThresholdMs <span class="token operator">&gt;</span> <span class="token number">0</span><span class="token punctuation">)</span> <span class="token operator">&amp;&amp;</span> <span class="token punctuation">(</span>msg<span class="token punctuation">.</span>when <span class="token operator">&gt;</span> <span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">final</span> <span class="token keyword">boolean</span> logSlowDispatch <span class="token operator">=</span> <span class="token punctuation">(</span>slowDispatchThresholdMs <span class="token operator">&gt;</span> <span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

            <span class="token keyword">final</span> <span class="token keyword">boolean</span> needStartTime <span class="token operator">=</span> logSlowDelivery <span class="token operator">||</span> logSlowDispatch<span class="token punctuation">;</span>
            <span class="token keyword">final</span> <span class="token keyword">boolean</span> needEndTime <span class="token operator">=</span> logSlowDispatch<span class="token punctuation">;</span>

            <span class="token keyword">if</span> <span class="token punctuation">(</span>traceTag <span class="token operator">!=</span> <span class="token number">0</span> <span class="token operator">&amp;&amp;</span> <span class="token class-name">Trace</span><span class="token punctuation">.</span><span class="token function">isTagEnabled</span><span class="token punctuation">(</span>traceTag<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
                <span class="token class-name">Trace</span><span class="token punctuation">.</span><span class="token function">traceBegin</span><span class="token punctuation">(</span>traceTag<span class="token punctuation">,</span> msg<span class="token punctuation">.</span>target<span class="token punctuation">.</span><span class="token function">getTraceName</span><span class="token punctuation">(</span>msg<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">}</span>

            <span class="token keyword">final</span> <span class="token keyword">long</span> dispatchStart <span class="token operator">=</span> needStartTime <span class="token operator">?</span> <span class="token class-name">SystemClock</span><span class="token punctuation">.</span><span class="token function">uptimeMillis</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">:</span> <span class="token number">0</span><span class="token punctuation">;</span>
            <span class="token keyword">final</span> <span class="token keyword">long</span> dispatchEnd<span class="token punctuation">;</span>
            <span class="token keyword">try</span> <span class="token punctuation">{</span>
                <span class="token comment">//msg.target为发送该消息的Handler对象</span>
                <span class="token comment">//发送的消息最终通过dispatchMessage()进行处理</span>
                msg<span class="token punctuation">.</span>target<span class="token punctuation">.</span><span class="token function">dispatchMessage</span><span class="token punctuation">(</span>msg<span class="token punctuation">)</span><span class="token punctuation">;</span>
                dispatchEnd <span class="token operator">=</span> needEndTime <span class="token operator">?</span> <span class="token class-name">SystemClock</span><span class="token punctuation">.</span><span class="token function">uptimeMillis</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">:</span> <span class="token number">0</span><span class="token punctuation">;</span>
            <span class="token punctuation">}</span> <span class="token keyword">finally</span> <span class="token punctuation">{</span>
                <span class="token keyword">if</span> <span class="token punctuation">(</span>traceTag <span class="token operator">!=</span> <span class="token number">0</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
                    <span class="token class-name">Trace</span><span class="token punctuation">.</span><span class="token function">traceEnd</span><span class="token punctuation">(</span>traceTag<span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token punctuation">}</span>
            <span class="token punctuation">}</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span>logSlowDelivery<span class="token punctuation">)</span> <span class="token punctuation">{</span>
                <span class="token keyword">if</span> <span class="token punctuation">(</span>slowDeliveryDetected<span class="token punctuation">)</span> <span class="token punctuation">{</span>
                    <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token punctuation">(</span>dispatchStart <span class="token operator">-</span> msg<span class="token punctuation">.</span>when<span class="token punctuation">)</span> <span class="token operator">&lt;=</span> <span class="token number">10</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
                        <span class="token class-name">Slog</span><span class="token punctuation">.</span><span class="token function">w</span><span class="token punctuation">(</span><span class="token constant">TAG</span><span class="token punctuation">,</span> <span class="token string">&quot;Drained&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                        slowDeliveryDetected <span class="token operator">=</span> <span class="token boolean">false</span><span class="token punctuation">;</span>
                    <span class="token punctuation">}</span>
                <span class="token punctuation">}</span> <span class="token keyword">else</span> <span class="token punctuation">{</span>
                    <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token function">showSlowLog</span><span class="token punctuation">(</span>slowDeliveryThresholdMs<span class="token punctuation">,</span> msg<span class="token punctuation">.</span>when<span class="token punctuation">,</span> dispatchStart<span class="token punctuation">,</span> <span class="token string">&quot;delivery&quot;</span><span class="token punctuation">,</span>
                            msg<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
                        <span class="token comment">// Once we write a slow delivery log, suppress until the queue drains.</span>
                        slowDeliveryDetected <span class="token operator">=</span> <span class="token boolean">true</span><span class="token punctuation">;</span>
                    <span class="token punctuation">}</span>
                <span class="token punctuation">}</span>
            <span class="token punctuation">}</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span>logSlowDispatch<span class="token punctuation">)</span> <span class="token punctuation">{</span>
                <span class="token function">showSlowLog</span><span class="token punctuation">(</span>slowDispatchThresholdMs<span class="token punctuation">,</span> dispatchStart<span class="token punctuation">,</span> dispatchEnd<span class="token punctuation">,</span> <span class="token string">&quot;dispatch&quot;</span><span class="token punctuation">,</span> msg<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">}</span>

            <span class="token keyword">if</span> <span class="token punctuation">(</span>logging <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
                logging<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">&quot;&lt;&lt;&lt;&lt;&lt; Finished to &quot;</span> <span class="token operator">+</span> msg<span class="token punctuation">.</span>target <span class="token operator">+</span> <span class="token string">&quot; &quot;</span> <span class="token operator">+</span> msg<span class="token punctuation">.</span>callback<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">}</span>

            <span class="token comment">// Make sure that during the course of dispatching the</span>
            <span class="token comment">// identity of the thread wasn't corrupted.</span>
            <span class="token keyword">final</span> <span class="token keyword">long</span> newIdent <span class="token operator">=</span> <span class="token class-name">Binder</span><span class="token punctuation">.</span><span class="token function">clearCallingIdentity</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span>ident <span class="token operator">!=</span> newIdent<span class="token punctuation">)</span> <span class="token punctuation">{</span>
                <span class="token class-name">Log</span><span class="token punctuation">.</span><span class="token function">wtf</span><span class="token punctuation">(</span><span class="token constant">TAG</span><span class="token punctuation">,</span> <span class="token string">&quot;Thread identity changed from 0x&quot;</span>
                        <span class="token operator">+</span> <span class="token class-name">Long</span><span class="token punctuation">.</span><span class="token function">toHexString</span><span class="token punctuation">(</span>ident<span class="token punctuation">)</span> <span class="token operator">+</span> <span class="token string">&quot; to 0x&quot;</span>
                        <span class="token operator">+</span> <span class="token class-name">Long</span><span class="token punctuation">.</span><span class="token function">toHexString</span><span class="token punctuation">(</span>newIdent<span class="token punctuation">)</span> <span class="token operator">+</span> <span class="token string">&quot; while dispatching to &quot;</span>
                        <span class="token operator">+</span> msg<span class="token punctuation">.</span>target<span class="token punctuation">.</span><span class="token function">getClass</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getName</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">+</span> <span class="token string">&quot; &quot;</span>
                        <span class="token operator">+</span> msg<span class="token punctuation">.</span>callback <span class="token operator">+</span> <span class="token string">&quot; what=&quot;</span> <span class="token operator">+</span> msg<span class="token punctuation">.</span>what<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">}</span>

            msg<span class="token punctuation">.</span><span class="token function">recycleUnchecked</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br><span class="line-number">16</span><br><span class="line-number">17</span><br><span class="line-number">18</span><br><span class="line-number">19</span><br><span class="line-number">20</span><br><span class="line-number">21</span><br><span class="line-number">22</span><br><span class="line-number">23</span><br><span class="line-number">24</span><br><span class="line-number">25</span><br><span class="line-number">26</span><br><span class="line-number">27</span><br><span class="line-number">28</span><br><span class="line-number">29</span><br><span class="line-number">30</span><br><span class="line-number">31</span><br><span class="line-number">32</span><br><span class="line-number">33</span><br><span class="line-number">34</span><br><span class="line-number">35</span><br><span class="line-number">36</span><br><span class="line-number">37</span><br><span class="line-number">38</span><br><span class="line-number">39</span><br><span class="line-number">40</span><br><span class="line-number">41</span><br><span class="line-number">42</span><br><span class="line-number">43</span><br><span class="line-number">44</span><br><span class="line-number">45</span><br><span class="line-number">46</span><br><span class="line-number">47</span><br><span class="line-number">48</span><br><span class="line-number">49</span><br><span class="line-number">50</span><br><span class="line-number">51</span><br><span class="line-number">52</span><br><span class="line-number">53</span><br><span class="line-number">54</span><br><span class="line-number">55</span><br><span class="line-number">56</span><br><span class="line-number">57</span><br><span class="line-number">58</span><br><span class="line-number">59</span><br><span class="line-number">60</span><br><span class="line-number">61</span><br><span class="line-number">62</span><br><span class="line-number">63</span><br><span class="line-number">64</span><br><span class="line-number">65</span><br><span class="line-number">66</span><br><span class="line-number">67</span><br><span class="line-number">68</span><br><span class="line-number">69</span><br><span class="line-number">70</span><br><span class="line-number">71</span><br><span class="line-number">72</span><br><span class="line-number">73</span><br><span class="line-number">74</span><br><span class="line-number">75</span><br><span class="line-number">76</span><br><span class="line-number">77</span><br><span class="line-number">78</span><br><span class="line-number">79</span><br><span class="line-number">80</span><br><span class="line-number">81</span><br><span class="line-number">82</span><br><span class="line-number">83</span><br><span class="line-number">84</span><br><span class="line-number">85</span><br><span class="line-number">86</span><br><span class="line-number">87</span><br><span class="line-number">88</span><br><span class="line-number">89</span><br><span class="line-number">90</span><br><span class="line-number">91</span><br><span class="line-number">92</span><br><span class="line-number">93</span><br><span class="line-number">94</span><br><span class="line-number">95</span><br><span class="line-number">96</span><br><span class="line-number">97</span><br><span class="line-number">98</span><br><span class="line-number">99</span><br><span class="line-number">100</span><br><span class="line-number">101</span><br><span class="line-number">102</span><br><span class="line-number">103</span><br><span class="line-number">104</span><br><span class="line-number">105</span><br><span class="line-number">106</span><br></div></div><h3 id="handler工作原理"><a href="#handler工作原理" class="header-anchor">#</a> Handler工作原理</h3> <p>Handler 的工作主要包含消息的发送和接收过程，消息的发送通过 post 的一系列方法以及 send 的一系列方法来实现。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">public</span> <span class="token keyword">final</span> <span class="token keyword">boolean</span> <span class="token function">sendMessageDelayed</span><span class="token punctuation">(</span><span class="token class-name">Message</span> msg<span class="token punctuation">,</span> <span class="token keyword">long</span> delayMillis<span class="token punctuation">)</span>
    <span class="token punctuation">{</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>delayMillis <span class="token operator">&lt;</span> <span class="token number">0</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
            delayMillis <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
        <span class="token keyword">return</span> <span class="token function">sendMessageAtTime</span><span class="token punctuation">(</span>msg<span class="token punctuation">,</span> <span class="token class-name">SystemClock</span><span class="token punctuation">.</span><span class="token function">uptimeMillis</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">+</span> delayMillis<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

  
    <span class="token keyword">public</span> <span class="token keyword">boolean</span> <span class="token function">sendMessageAtTime</span><span class="token punctuation">(</span><span class="token class-name">Message</span> msg<span class="token punctuation">,</span> <span class="token keyword">long</span> uptimeMillis<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token class-name">MessageQueue</span> queue <span class="token operator">=</span> mQueue<span class="token punctuation">;</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>queue <span class="token operator">==</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
            <span class="token class-name">RuntimeException</span> e <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">RuntimeException</span><span class="token punctuation">(</span>
                    <span class="token keyword">this</span> <span class="token operator">+</span> <span class="token string">&quot; sendMessageAtTime() called with no mQueue&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token class-name">Log</span><span class="token punctuation">.</span><span class="token function">w</span><span class="token punctuation">(</span><span class="token string">&quot;Looper&quot;</span><span class="token punctuation">,</span> e<span class="token punctuation">.</span><span class="token function">getMessage</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> e<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">return</span> <span class="token boolean">false</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
        <span class="token keyword">return</span> <span class="token function">enqueueMessage</span><span class="token punctuation">(</span>queue<span class="token punctuation">,</span> msg<span class="token punctuation">,</span> uptimeMillis<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    
    <span class="token keyword">public</span> <span class="token keyword">final</span> <span class="token keyword">boolean</span> <span class="token function">sendMessageAtFrontOfQueue</span><span class="token punctuation">(</span><span class="token class-name">Message</span> msg<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token class-name">MessageQueue</span> queue <span class="token operator">=</span> mQueue<span class="token punctuation">;</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>queue <span class="token operator">==</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
            <span class="token class-name">RuntimeException</span> e <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">RuntimeException</span><span class="token punctuation">(</span>
                <span class="token keyword">this</span> <span class="token operator">+</span> <span class="token string">&quot; sendMessageAtTime() called with no mQueue&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token class-name">Log</span><span class="token punctuation">.</span><span class="token function">w</span><span class="token punctuation">(</span><span class="token string">&quot;Looper&quot;</span><span class="token punctuation">,</span> e<span class="token punctuation">.</span><span class="token function">getMessage</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> e<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">return</span> <span class="token boolean">false</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
        <span class="token keyword">return</span> <span class="token function">enqueueMessage</span><span class="token punctuation">(</span>queue<span class="token punctuation">,</span> msg<span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br><span class="line-number">16</span><br><span class="line-number">17</span><br><span class="line-number">18</span><br><span class="line-number">19</span><br><span class="line-number">20</span><br><span class="line-number">21</span><br><span class="line-number">22</span><br><span class="line-number">23</span><br><span class="line-number">24</span><br><span class="line-number">25</span><br><span class="line-number">26</span><br><span class="line-number">27</span><br><span class="line-number">28</span><br><span class="line-number">29</span><br><span class="line-number">30</span><br><span class="line-number">31</span><br></div></div><p>可以发现，Handler 发送消息的过程仅仅时向消息对列中插入了一条消息，MessageQueue 的 next 方法就会返回这条消息给 Looper，Looper 接收后开始处理，最终消息由 Looper 交由 Handler 处理，即 Handler 的 dispatchMessage 方法调用。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">dispatchMessage</span><span class="token punctuation">(</span><span class="token class-name">Message</span> msg<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>msg<span class="token punctuation">.</span>callback <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
            <span class="token function">handleCallback</span><span class="token punctuation">(</span>msg<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span> <span class="token keyword">else</span> <span class="token punctuation">{</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span>mCallback <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
                <span class="token keyword">if</span> <span class="token punctuation">(</span>mCallback<span class="token punctuation">.</span><span class="token function">handleMessage</span><span class="token punctuation">(</span>msg<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
                    <span class="token keyword">return</span><span class="token punctuation">;</span>
                <span class="token punctuation">}</span>
            <span class="token punctuation">}</span>
            <span class="token function">handleMessage</span><span class="token punctuation">(</span>msg<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br></div></div><p>Message 的 callback 是一个 Runnable 对象，实际上就是 Handler 的 post 方法传递的 Runnable 参数。handleCallback 的逻辑如下：</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code> <span class="token keyword">private</span> <span class="token keyword">static</span> <span class="token keyword">void</span> <span class="token function">handleCallback</span><span class="token punctuation">(</span><span class="token class-name">Message</span> message<span class="token punctuation">)</span> <span class="token punctuation">{</span>
     message<span class="token punctuation">.</span>callback<span class="token punctuation">.</span><span class="token function">run</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
 <span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br></div></div><p>当 mCallback 不为 null 时就调用 mCallback 的 handleMessage 方法来处理消息，其定义如下：</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code>    <span class="token comment">/**
     * Callback interface you can use when instantiating a Handler to avoid
     * having to implement your own subclass of Handler.
     */</span>
    <span class="token keyword">public</span> <span class="token keyword">interface</span> <span class="token class-name">Callback</span> <span class="token punctuation">{</span>
        <span class="token comment">/**
         * @param msg A {@link android.os.Message Message} object
         * @return True if no further handling is desired
         */</span>
        <span class="token keyword">public</span> <span class="token keyword">boolean</span> <span class="token function">handleMessage</span><span class="token punctuation">(</span><span class="token class-name">Message</span> msg<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br></div></div><p>Handler 还有一个特殊的构造方法，就是通过一个特定的 Looper 来构造 Handler，其实现如下：</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">public</span> <span class="token class-name">Handler</span><span class="token punctuation">(</span><span class="token class-name">Looper</span> looper<span class="token punctuation">)</span><span class="token punctuation">{</span>
    <span class="token keyword">this</span><span class="token punctuation">(</span>looper<span class="token punctuation">,</span><span class="token keyword">null</span><span class="token punctuation">,</span><span class="token boolean">false</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br></div></div><p>Handler 的默认构造方法 public Handler() 会调用如下的构造方法，解释了在没有 Looper 的子线程中会引发程序异常的原因。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">public</span> <span class="token class-name">Handler</span><span class="token punctuation">(</span><span class="token class-name">Callback</span> callback<span class="token punctuation">,</span> <span class="token keyword">boolean</span> async<span class="token punctuation">)</span> <span class="token punctuation">{</span>
       <span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span>
        mLooper <span class="token operator">=</span> <span class="token class-name">Looper</span><span class="token punctuation">.</span><span class="token function">myLooper</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>mLooper <span class="token operator">==</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
            <span class="token keyword">throw</span> <span class="token keyword">new</span> <span class="token class-name">RuntimeException</span><span class="token punctuation">(</span>
                <span class="token string">&quot;Can't create handler inside thread &quot;</span> <span class="token operator">+</span> <span class="token class-name">Thread</span><span class="token punctuation">.</span><span class="token function">currentThread</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
                        <span class="token operator">+</span> <span class="token string">&quot; that has not called Looper.prepare()&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
        mQueue <span class="token operator">=</span> mLooper<span class="token punctuation">.</span>mQueue<span class="token punctuation">;</span>
        mCallback <span class="token operator">=</span> callback<span class="token punctuation">;</span>
        mAsynchronous <span class="token operator">=</span> async<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br></div></div><p>参考书籍：《Android开发艺术探索》/任玉刚 | 电子工业出版社</p></div></section> <footer class="page-edit"><!----> <div class="last-updated"><span class="prefix">最近更新时间: </span> <span class="time">5/6/2023, 6:41:13 PM</span></div></footer> <!----> <div class="comments-wrapper"><!----></div></main></div> <!----></div> <ul class="sub-sidebar sub-sidebar-wrapper" style="width:12rem;" data-v-6986a797 data-v-6f8f7dda><li class="level-3" data-v-6986a797><a href="/blogs/summary/2022/event-handler-parse.html#为什么主线程中可以直接使用handler" class="sidebar-link reco-side-为什么主线程中可以直接使用handler" data-v-6986a797>为什么主线程中可以直接使用Handler?</a></li><li class="level-3" data-v-6986a797><a href="/blogs/summary/2022/event-handler-parse.html#为什么android会提供handler" class="sidebar-link reco-side-为什么android会提供handler" data-v-6986a797>为什么Android会提供Handler?</a></li><li class="level-3" data-v-6986a797><a href="/blogs/summary/2022/event-handler-parse.html#为什么不允许子线程中访问ui呢" class="sidebar-link reco-side-为什么不允许子线程中访问ui呢" data-v-6986a797>为什么不允许子线程中访问UI呢？</a></li><li class="level-3" data-v-6986a797><a href="/blogs/summary/2022/event-handler-parse.html#为什么系统不对ui的访问加上锁机制呢" class="sidebar-link reco-side-为什么系统不对ui的访问加上锁机制呢" data-v-6986a797>为什么系统不对UI的访问加上锁机制呢？</a></li><li class="level-3" data-v-6986a797><a href="/blogs/summary/2022/event-handler-parse.html#handler的处理过程" class="sidebar-link reco-side-handler的处理过程" data-v-6986a797>Handler的处理过程</a></li><li class="level-3" data-v-6986a797><a href="/blogs/summary/2022/event-handler-parse.html#threadlocal-java8" class="sidebar-link reco-side-threadlocal-java8" data-v-6986a797>ThreadLocal (Java8)</a></li><li class="level-3" data-v-6986a797><a href="/blogs/summary/2022/event-handler-parse.html#messagequeue工作原理" class="sidebar-link reco-side-messagequeue工作原理" data-v-6986a797>MessageQueue工作原理</a></li><li class="level-3" data-v-6986a797><a href="/blogs/summary/2022/event-handler-parse.html#looper工作原理" class="sidebar-link reco-side-looper工作原理" data-v-6986a797>Looper工作原理</a></li><li class="level-3" data-v-6986a797><a href="/blogs/summary/2022/event-handler-parse.html#handler工作原理" class="sidebar-link reco-side-handler工作原理" data-v-6986a797>Handler工作原理</a></li></ul></div></div></div><div class="global-ui"><div class="back-to-ceiling" style="right:1rem;bottom:6rem;width:2.5rem;height:2.5rem;border-radius:.25rem;line-height:2.5rem;display:none;" data-v-c6073ba8 data-v-c6073ba8><svg t="1574745035067" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5404" class="icon" data-v-c6073ba8><path d="M526.60727968 10.90185116a27.675 27.675 0 0 0-29.21455937 0c-131.36607665 82.28402758-218.69155461 228.01873535-218.69155402 394.07834331a462.20625001 462.20625001 0 0 0 5.36959153 69.94390903c1.00431239 6.55289093-0.34802892 13.13561351-3.76865779 18.80351572-32.63518765 54.11355614-51.75690182 118.55860487-51.7569018 187.94566865a371.06718723 371.06718723 0 0 0 11.50484808 91.98906777c6.53300375 25.50556257 41.68394495 28.14064038 52.69160883 4.22606766 17.37162448-37.73630017 42.14135425-72.50938081 72.80769204-103.21549295 2.18761121 3.04276886 4.15646224 6.24463696 6.40373557 9.22774369a1871.4375 1871.4375 0 0 0 140.04691725 5.34970492 1866.36093723 1866.36093723 0 0 0 140.04691723-5.34970492c2.24727335-2.98310674 4.21612437-6.18497483 6.3937923-9.2178004 30.66633723 30.70611158 55.4360664 65.4791928 72.80769147 103.21549355 11.00766384 23.91457269 46.15860503 21.27949489 52.69160879-4.22606768a371.15156223 371.15156223 0 0 0 11.514792-91.99901164c0-69.36717486-19.13165746-133.82216804-51.75690182-187.92578088-3.42062944-5.66790279-4.76302748-12.26056868-3.76865837-18.80351632a462.20625001 462.20625001 0 0 0 5.36959269-69.943909c-0.00994388-166.08943902-87.32547796-311.81420293-218.6915546-394.09823051zM605.93803103 357.87693858a93.93749974 93.93749974 0 1 1-187.89594924 6.1e-7 93.93749974 93.93749974 0 0 1 187.89594924-6.1e-7z" p-id="5405" data-v-c6073ba8></path><path d="M429.50777625 765.63860547C429.50777625 803.39355007 466.44236686 1000.39046097 512.00932183 1000.39046097c45.56695499 0 82.4922232-197.00623328 82.5015456-234.7518555 0-37.75494459-36.9345906-68.35043303-82.4922232-68.34111062-45.57627738-0.00932239-82.52019037 30.59548842-82.51086798 68.34111062z" p-id="5406" data-v-c6073ba8></path></svg></div></div></div>
    <script src="/assets/js/app.371ed010.js" defer></script><script src="/assets/js/3.fe7e7b6d.js" defer></script><script src="/assets/js/1.adb5634c.js" defer></script><script src="/assets/js/20.8284a0ff.js" defer></script>
  </body>
</html>
